import java.util.Hashtable;
import java.util.Enumeration;
import java.util.StringTokenizer;
public class Graph extends PowerHash
  {
  protected Machine machine;
  protected State start;
  protected State selected;
  private boolean locked;
  public Graph(Machine machine)
    {
    this.machine=machine;
    locked=true;
    }
  public void changeAccepting()
    {
    if(selected!=null)
      {
      selected.changeAccepting();
      }
    }
  public void setStart()
    {
    if(selected!=null) start=selected;
    }
  public void setStart(State start)
    {
    this.start=start;
    }
  public State getStart()
    {
    return start;
    }
  public void setSelected(State selected)
    {
    this.selected=selected;
    }
  public State getSelected()
    {
    return selected;
    }
  public void addState(State state)
    {
    put(state);
    }
  public void removeState(State state)
    {
    if(state!=null)
      {
      remove(state);
      Enumeration k1s=keys();
      while(k1s.hasMoreElements()) //per tutti gli stati
        {
        Object k1=k1s.nextElement();
        Hashtable h=get(k1);
        Enumeration k2s=h.keys();
        while(k2s.hasMoreElements()) //per tutte le etichette
          {
          Object k2=k2s.nextElement();
          Transition t=(Transition)h.get(k2);
          if(t.getEnd()==state) h.remove(k2);
          }
        }
      }
    }
  public Enumeration states()
    {
    return keys();
    }
  public Hashtable exitingTransitions(State state)
    {
    return get(state);
    }
  public Transition getTransition(State state,String read)
    {
    return (Transition)get(state,read);
    }
  public void addTransition(Transition t)
    {
    put(t.getStart(),t.getRead(),t);
    }
  public void removeTransition(Transition t)
    {
    if(t!=null) remove(t.getStart(),t.getRead());
    }
  public void tryToLock(State current)
    {
    if(current!=null)
      {
      String label=current.getLabel();
      if(!label.equals("")) locked=true;
      Enumeration states=states();
      while(states.hasMoreElements()&&locked)
        {
        State state=(State)states.nextElement();
        if(state!=current&&state.getLabel().equals(label))
          {
          locked=false;
          }
        }
      }
    else locked=true;
    }
  public void unlock()
    {
    locked=false;
    }
  public boolean isLocked()
    {
    return locked;
    }
  public boolean isUnlocked()
    {
    return !locked;
    }
    
  public State getState(String label)
    {
    Enumeration states=states();
    while(states.hasMoreElements())
      {
      State state=(State)states.nextElement();
      if(state.getLabel().equals(label)) return state;
      }
    return null;
    }
  }
